import 'package:flutter/services.dart';
import 'package:honeypotflutter/public/public_alert.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class HLCameraImage {
  /*
  * 调用相机
  * */
  static Future<XFile> camera() async {
    final ImagePicker _picker = ImagePicker();
    try {
      var image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) {
        return Future.error("无数据");
      }
      return image;
    } catch (error) {
      PlatformException plat = error as PlatformException;
      if (plat.code == "camera_access_denied") {
        HLAlert.showSureCancelAlert(
            title: "权限提示",
            message: "您已拒绝APP访问使用您的相机，如需继续使用，请至设置中开启您的相机权限",
            cancelLabel: "取消",
            okLabel: "前往设置",
            sureAction: (bool ok) {
              if (ok) {
                openAppSettings();
              }
            });
      }
      return Future.error(error);
    }
  }

  /*
  * 相册
  * */
  static Future<List<XFile>> photo({int max = 1}) async {
    final ImagePicker _picker = ImagePicker();
    try {
      if (max <= 1) {
        var image = await _picker.pickImage(source: ImageSource.gallery);
        if (image == null) {
          return Future.error("无数据");
        }
        return [image];
      }
      var images = await _picker.pickMultiImage(limit: max);
      return images;
    } catch (error) {
      PlatformException plat = error as PlatformException;
      if (plat.code == "photo_access_denied") {
        HLAlert.showSureCancelAlert(
            title: "权限提示",
            message: "您已拒绝APP访问使用您的相册，如需继续使用，请至设置中开启您的相册权限",
            cancelLabel: "取消",
            okLabel: "前往设置",
            sureAction: (bool ok) {
              if (ok) {
                openAppSettings();
              }
            });
      }
      return Future.error(error);
    }
  }
}
